# -*- coding: utf-8 -*-
import __main__
from appengine_utilities import sessions
from appengine_utilities import flash
from appengine_utilities import event
from appengine_utilities import cache
from appengine_utilities.rotmodel import ROTModel

import wsgiref.handlers
import urllib2
import urllib
import base64
import simplejson
from BeautifulSoup import BeautifulSoup,Tag,NavigableString

from google.appengine.ext import webapp
import xmw
import xmw.sites
from xmw.db import ds
import logging
import zlib
def get_prop_from_soup(soup,prop_name):
    tag=soup.find('td',{'id':prop_name})
    return tag.contents[0]
"""        
def read_thread(site,post_url):
    try:
        url=site+"/tianya/get_thread_by_url?url="
        #param="url="+post_url
    
        addr=url+urllib.quote(post_url)
        logging.log( logging.INFO, "read url :%s"%str(addr))
        sock=urllib2.urlopen(addr  ) 
        html=sock.read()
        sock.close() 
        soup= BeautifulSoup(html)  
        thread_id="xx"
        thread_id=get_prop_from_soup(soup,"thread_id")
        thread=xmw.Thread(thread_id = thread_id)
        thread.title=get_prop_from_soup(soup,"title")
        thread.chrAuthor=get_prop_from_soup(soup,"chrAuthor")
        thread.type=get_prop_from_soup(soup,"type")
        thread.page_cnt=int(get_prop_from_soup(soup,"page_cnt"))
        thread.type=get_prop_from_soup(soup,"type")
        thread.offset=int(get_prop_from_soup(soup,"offset"))
        thread.type=get_prop_from_soup(soup,"type")
        #thread.created=xmw.ascii_to_datetime(get_prop_from_soup(soup,"created"))
        thread.type=get_prop_from_soup(soup,"type")
        thread.type=get_prop_from_soup(soup,"type")
        thread.type=get_prop_from_soup(soup,"type")
        thread.type=get_prop_from_soup(soup,"type")
        #print "GBBBBBBBBB"
        #print "xx=%s"%soup.prettify()
        
        
        return (thread,None)
    except Exception,ex:
        import traceback
        traceback.print_exc()
        return (None,ex)

"""
    
class MainPage(xmw.RequestHandler):
    def get_thread_by_url_local(self,url):
        q_thread=xmw.Thread.all()
        q_thread.filter("lst_page_url =",url)
        thread=q_thread.get()
        return thread
        
    def get(self):
        
        (post_url,e)=self.get_key_from_GET("post_url")
        
        if e is not None:
            self.redirect("/")
        post_url=post_url.decode("utf-8")
        (title,e)=self.get_key_from_GET("title")
        logging.log( logging.INFO, "title :%s"% (title))
        #title   =title.encode("utf-8")
        title=title.replace("@","=")
        title=title.replace("*","+")
        title=base64.decodestring(title)
        title=zlib.decompress(title)
        #title=urllib.unquote(title)
        self.sess = sessions.Session()
        self.cookie_sess = sessions.Session(writer="cookie")          
        session_user =None
        if not self.sess.has_key("user"):
            #not login
            #session_user=self.sess["user"]
            template_values = {
                           "login_action":"/subscribe"
                           }
            url=self.get_url()
            args=self.request.arguments()
            params=""
            for arg in args:
                #params=arg+"="+urllib.quote(self.request.GET[arg])
                logging.log( logging.INFO, "arg :%s"% (arg))
                params=params+arg+"="+self.request.GET[arg]
                params=params+"&"
            #params=urllib.quote(params.decode("utf-8"))
            #logging.log( logging.INFO, "type:%s"%str(type(self.request.GET)))
            #logging.log( logging.INFO, "subscribe url: %s\n params :%s"% (url,str(params)))
            self.sess["login_action"] = ds.Login_Action(action=url,params=params)
            self.sess["login_action"].put()
            #self.redirect("/")
            self.render_template(template_values, '../html/login.html')
            return
        else:
            session_user=self.sess["user"]
        
        #thread=self.get_thread_by_url_local(url)
        
        #if thread is None:
        #bot_site=xmw.sites.get_bot_site()
        #print "AAA"
        #(thread,e)=read_thread(bot_site,post_url)
        #(thread,e)=read_thread(post_url)
        
        #print "thread=%s"%str(thread)
        template_values = {
                           "post_url":post_url,
                           "session_user":session_user,
                           #"thread":thread,
                           #'title':cgi.escape(title)
                           'title':title
                           }    
        self.render_template(template_values, '../html/subscribe.html')
        
    

def main():
  application = webapp.WSGIApplication(
                                       [('/subscribe', MainPage)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()